package com.imc.api.user.controller;

import com.imc.api.order.repository.IUserOrgAccountRepository;
import com.imc.api.user.service.ApiUserService;
import com.imc.api.user.tuple.UserTuple;
import com.imc.core.annotation.Logs;
import com.imc.core.utils.MysqlUtil;
import com.imc.core.utils.UploadUtiles;
import com.imc.platform.base.user.dao.mapper.IUserMapper;
import com.imc.platform.base.user.dao.repository.UserRepository;
import com.imc.platform.base.user.pojo.User;
import com.imc.platform.base.user.pojo.UserSub;
import com.twp.common.component.process.exception.combo.IComboExecptionForTFunc;
import com.twp.common.tuple.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by tanweiping on 2018/10/9.
 */
@RequestMapping("/api/user")
@RestController
@Slf4j
public class ApiUserController {
    public static final String imgUrl = "/images/user/";
    @Autowired
    IComboExecptionForTFunc iComboExecptionForTFunc;

    @Autowired
    ApiUserService apiUserService;
    @Autowired
    UploadUtiles uploadUtiles;
    @Autowired
    IUserMapper userMapper;

    @Autowired
    IUserOrgAccountRepository iUserOrgAccountRepository;

    @Autowired
    MysqlUtil mysqlUtil;
    /*
     * YT  2018/10/28 22:10
     * 方法描述：补充用户信息失败
     */
    @PostMapping("/append")
    ResultDTO append(@RequestBody UserTuple userTuple, Principal principal,HttpServletRequest request) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    request.getSession().setAttribute("currentUser",apiUserService.appendUserMessage(userTuple, principal));
                },
                (e, t) -> {
                    t.setIsSuccess(false);
                    t.setMessage("补充用户信息失败");
                }
        );
    }

    @PostMapping("/addUserSubaccount")
    @ResponseBody
    public ResultDTO addUserSubaccount(
            HttpServletRequest request,
            String photo,
            @RequestParam(value = "file",required = false) MultipartFile file
    ){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {

                    String fileName = "";

                    if (file!=null){
                        //入库路径
                        String realPath =uploadUtiles.getCurrentAddress(imgUrl);
                        //上传路径
                        String savePath=uploadUtiles.getLocationAddress(imgUrl);
                        fileName = realPath + uploadUtiles.getUpImg(savePath, file);
                    }

                        HttpSession session = request.getSession();
                        User user=(User) session.getAttribute("currentUser");
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                        UserSub userSub= UserSub.builder()
                                .parentId(user.getId())
                                .name(request.getParameter("name"))
                                .orgId(Integer.parseInt(request.getParameter("orgId")))
                                .code(request.getParameter("code"))
                                .sex(request.getParameter("sex"))
                                .birth(request.getParameter("birth"))
                                .address(request.getParameter("address"))
                                .createTime(df.format(new Date()))
                                //.photo(realPath+fileName)
                                .build();
                        if(!StringUtils.isEmpty(fileName)){
                            userSub.setPhoto(fileName);
                        }else if(!StringUtils.isEmpty(photo)){
                            userSub.setPhoto(photo);
                        }
                        String id=request.getParameter("id");
                        if(StringUtils.isEmpty(id)){
                            Map<String,Object>retMap=new HashMap<>();
                            apiUserService.addUserSubaccount(userSub);
                            retMap.put("id",userSub.getId());
                            t.setData(retMap);
                            t.setMessage("添加成功");
                        }else {
                            userSub.setId(Integer.parseInt(id));
                            apiUserService.updateUserSubaccount(userSub);
                            t.setMessage("修改成功");
                        }

                    }
                ,
                (e, t) -> {
                    t.setCode("201");
                    t.setIsSuccess(false);
                    t.setMessage("子账户操作失败");
                }
        );
    }

    /*
     * YT  2018/10/28 22:10
     * 方法描述：获取用户信息
     */
    @GetMapping("/getUserInf")
    @ResponseBody
    ResultDTO getUserInf(Principal principal) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    User user = mysqlUtil.getUserByLoginName(principal.getName());

                    Integer account =  iUserOrgAccountRepository.accountByUserId(String.valueOf(user.getId()));

                    if (account!=null){
                        user.setClassTime(account);
                    }

                    user.setUserSubs(userMapper.queryUserSubList(String.valueOf(user.getId())));
                    if (!"".equals(user) && null != user) {
                        t.setIsSuccess(true);
                        t.setMessage("获取用户信息成功");
                        t.setCode("200");
                        t.setData(user);
                    } else {
                        t.setMessage("用户凭证已过期,请重新登陆");
                        t.setIsSuccess(false);
                    }
                }, (e, t) -> {
                    t.setIsSuccess(false);
                    t.setMessage("获取用户信息失败");
                }
        );
    }

    @PostMapping("updateUserImg")
    @ResponseBody
    ResultDTO upUserImgByUserId(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    HttpSession session = request.getSession();
                    User user=(User) session.getAttribute("currentUser");
                    //入库路径
                    String realPath =uploadUtiles.getCurrentAddress(imgUrl);
                    //上传路径
                    String savePath=uploadUtiles.getLocationAddress(imgUrl);
                    String fileName = uploadUtiles.getUpImg(savePath, file);
                    if (null != fileName && !"".equals(fileName)) {
                        userMapper.updateUserImgByUserId(realPath+fileName,String.valueOf(user.getId()));
                        user.setPhoto(realPath+fileName);
                        session.setAttribute("currentUser",user);
                        t.setIsSuccess(true);
                        t.setData(realPath+fileName);
                    } else {
                        log.info("图片上传失败");
                        t.setIsSuccess(false);
                        t.setMessage("图片上传失败");
                    }
                },
                (e,t)->{
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("修改用户头像失败");
                }
        );
    }

    @GetMapping("/queryUserSubaccount")
    @ResponseBody
    ResultDTO queryUserSubaccount(String subaccountId){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    t.setData(userMapper.queryUserSub(subaccountId));
                    t.setMessage("获取子账号成功");
                }, (e, t) -> {
                    t.setIsSuccess(false);
                    t.setMessage("获取子账号信息失败");
                }
        );
    }

    @GetMapping("/delUserSubaccount")
    @ResponseBody
    ResultDTO delUserSubaccount(String subaccountId){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    userMapper.delUserSub(subaccountId);
                    t.setMessage("删除子账号成功");
                }, (e, t) -> {
                    t.setIsSuccess(false);
                    t.setMessage("删除子账号信息失败");
                }
        );
    }
}